import Category from '../../models/category';
import Service from '../../models/service'

import { throttle } from '../../utils/utils'

const service = new Service()

Page({

  /**
   * 页面的初始数据
   */
  data: {
    tabs: ['全部服务', '在提供', '正在找'],
    tabIndex: 0,
    categoryId: 0,
    categoryList: [],
    serviceList: [],
    loading: true
  },

  async _getServiceList () {
    const serviceList = await service.reset().getServiceList(this.data.categoryId, this.data.tabIndex)
    console.log('玩两把', serviceList);
    this.setData({
      serviceList: serviceList
    })
  },

  async _getCategoryList () {
    const categoryList = await Category.getCategoryListWithAll()
    this.setData({
      categoryList
    })
  },

  handleTabChange (event) {
    console.log('tab改变',event);
    this.data.tabIndex = event.detail.index
    this._getServiceList()
  },

  // throttle
  handleCategoryChange: throttle(function (event) {
    
    console.log(event);
    if (this.data.categoryId === event.currentTarget.dataset.id) {
      return
    }
    this.data.categoryId = event.currentTarget.dataset.id
    this._getServiceList()
  }),

  handleSelectService: function (event) {
    console.log(event);
    const sevice = event.currentTarget.dataset.service
    wx.navigateTo({
      url: '/pages/service-detail/service-detail?id='+service.id
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: async function (options) {
    wx.login({
      success: function(res) {
        console.log(res);
        if(res.code) {
          
        } else {
          console.log(res.errMsg)
        }
      }
    })
    await this._getServiceList()
    await this._getCategoryList()
    this.setData({
      loading: false
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: async function () {
    console.log('onPullDownRefresh');

    this._getServiceList()
    wx.stopPullDownRefresh()
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: async function () {
    console.log('onReachBottom');
    if (!service.hasMoreData) {
      return
    }
    const serviceList = await service.getServiceList(this.data.categoryId, this.data.tabIndex)
    this.setData({serviceList})
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})